package com.sc.nft.admin.task;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.sc.nft.admin.service.QywxService;
import com.sc.nft.dao.*;
import com.sc.nft.dto.CollectionEcologyCreateVO;
import com.sc.nft.dto.UserEcologyHatchIncomeRecordDao;
import com.sc.nft.dto.UserEcologyHatchRecordsDao;
import com.sc.nft.enums.DaoLevelTypeEnum;
import com.sc.nft.enums.MarketTypeEnum;
import com.sc.nft.enums.PayTypeEnum;
import com.sc.nft.mapper.SecondOrderMapper;
import com.sc.nft.mapper.UserCollectionMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
@RequiredArgsConstructor
public class SandQywxNoticTask {
    private final UserEcologyHatchRecordsDao userEcologyHatchRecordsDao;
    private final SecondOrderDao secondOrderDao;
    private final UserCollectionDao userCollectionDao;
    private final SecondOrderMapper secondOrderMapper;
    private final UserCollectionMapper userCollectionMapper;
    private final SandTransferRecordDao sandTransferRecordDao;
    private final PayOrderDao payOrderDao;
    private final DaoTransferDao daoTransferDao;
    private final QywxService qywxService;
    private final UserEcologyHatchIncomeRecordDao userEcologyHatchIncomeRecordDao;
    private final RedisTemplate redisTemplate;
    String oneTimeKey = "PUSH_TIME";
    public static final List<String> account = Lists.newArrayList("YiLuXiangYang","MaJiHua", "sun", "LaoRenYuHai.Xian", "ChenYuanChun");
    public static final List<String> account1 = Lists.newArrayList("YiLuXiangYang","MaJiHua", "sun", "LaoRenYuHai.Xian", "ChenYuanChun");
    public static final List<String> adminAccount = Lists.newArrayList("e154ac8261921447c5aec6de0f989e6c", "sun", "CaiMaoJian", "LaoRenYuHai.Xian");

    @Scheduled(cron = "00 30 00 * * ?")
    public void allSend() throws Exception {
        Long increment = redisTemplate.opsForValue().increment(oneTimeKey);
        redisTemplate.expire(oneTimeKey, 1, TimeUnit.MINUTES);
        if (increment > 1) {
            return;
        }
        sendMsg();
        sendMsg2();
        sendMsg4();
        sendMsg5();
        sendMsg6();
    }

    private void sendMsg() {

        StringBuffer content = new StringBuffer();
        DateTime yesterday = DateUtil.yesterday();
        DateTime startTime = DateUtil.beginOfDay(yesterday);
        DateTime endTime = DateUtil.endOfDay(yesterday);
        List<CollectionEcologyCreateVO> ecologyCollectionCreateCount = userCollectionMapper.getEcologyCollectionCreateCount(startTime, endTime);
        content.append("昨日生态产出数量（铸造+重铸+兑换+合成）: \n");
        for (CollectionEcologyCreateVO collectionEcologyCreateVO : ecologyCollectionCreateCount) {
            content.append(collectionEcologyCreateVO.getFirstTitle()).append(": ").append(collectionEcologyCreateVO.getCreateCount()).append("\n");
        }
        account.forEach(item->{
            qywxService.sendWeChatMessage(content.toString(),item);
        });
    }


    public void sendMsg5() throws Exception {


        DateTime yesterday = DateUtil.yesterday();
        DateTime startTime = DateUtil.beginOfDay(yesterday);
        DateTime endTime = DateUtil.endOfDay(yesterday);

        BigDecimal charge2 = secondOrderMapper.getToDaySumCharge(1,2, startTime, endTime).multiply(BigDecimal.valueOf(0.93)).setScale(2,BigDecimal.ROUND_HALF_UP);
        BigDecimal charge4 = secondOrderMapper.getToDaySumCharge(4,2, startTime, endTime).multiply(BigDecimal.valueOf(0.93)).setScale(2,BigDecimal.ROUND_HALF_UP);
        BigDecimal charge6 = secondOrderMapper.getToDaySumCharge(2,2, startTime, endTime).multiply(BigDecimal.valueOf(0.93)).setScale(2,BigDecimal.ROUND_HALF_UP);
        Integer buyUserCount = secondOrderMapper.getMarketUserCount(MarketTypeEnum.FREE_MARKET.getCode(),startTime,endTime);
        Integer freeUserCount = userCollectionDao.getFreeUserCount();
        String content =
                "今日手续费收益：\n"+
                        "自由市场手续费（全部）："+charge4+"元\n"+
                        "自由市场手续费（会员卖）："+charge2+"元\n"+
                        "自由市场手续费（会员买）："+charge6+"元\n"+
                        "总自由市场会员人数："+freeUserCount+"\n"+
                        "昨日自由市场交易人数："+buyUserCount+"\n"
                ;
        account.forEach(item->{
            qywxService.sendWeChatMessage(content,item);
        });


    }


    public void sendMsg6() throws Exception {

        BigDecimal value10000 = userEcologyHatchRecordsDao.getSumMarketValueLessThan(0, 10000);
        BigDecimal value50000 = userEcologyHatchRecordsDao.getSumMarketValueLessThan(10001, 50000);
        BigDecimal value100000 = userEcologyHatchRecordsDao.getSumMarketValueLessThan(50001, 100000);
        BigDecimal value150000 = userEcologyHatchRecordsDao.getSumMarketValueLessThan(100001, 150000);
        BigDecimal value200000 = userEcologyHatchRecordsDao.getSumMarketValueLessThan(150001, 200000);
        BigDecimal value300000 = userEcologyHatchRecordsDao.getSumMarketValueLessThan(200001, 300000);
        BigDecimal value500000 = userEcologyHatchRecordsDao.getSumMarketValueLessThan(300001, 500000);
        BigDecimal more500000 = userEcologyHatchRecordsDao.getSumMarketValueLessThan(500001, 99999999);
        BigDecimal sumValue = value10000.add(value50000).add(value100000).add(value150000).add(value200000).add(value300000).add(value500000).add(more500000);


        BigDecimal count10000 = userEcologyHatchRecordsDao.getSumUserCountLessThan(0, 10000);
        BigDecimal count50000 = userEcologyHatchRecordsDao.getSumUserCountLessThan(10001, 50000);
        BigDecimal count100000 = userEcologyHatchRecordsDao.getSumUserCountLessThan(50001, 100000);
        BigDecimal count150000 = userEcologyHatchRecordsDao.getSumUserCountLessThan(100001, 150000);
        BigDecimal count200000 = userEcologyHatchRecordsDao.getSumUserCountLessThan(150001, 200000);
        BigDecimal count300000 = userEcologyHatchRecordsDao.getSumUserCountLessThan(200001, 300000);
        BigDecimal count500000 = userEcologyHatchRecordsDao.getSumUserCountLessThan(300001, 500000);
        BigDecimal moreCount500000 = userEcologyHatchRecordsDao.getSumUserCountLessThan(500001, 99999999);
        BigDecimal sumCount = count10000.add(count50000).add(count100000).add(count150000).add(count200000).add(count300000).add(count500000).add(moreCount500000);

        String content =
                "生态熔炼持仓总值：" + sumValue + "\n"
                        + "生态熔炼持仓总人数：" + sumCount + "\n"
                        + "小于10000：总市值" + value10000 + ",占比：" + value10000.divide(sumValue, 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)).setScale(2)
                        + "% 人数：" + count10000 + ",占比：" + count10000.divide(sumCount, 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)).setScale(2) + "\n"
                        + "10000-50000：总市值" + value50000 + ",占比：" + value50000.divide(sumValue, 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)).setScale(2)
                        + "% 人数：" + count50000 + ",占比：" + count50000.divide(sumCount, 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)).setScale(2) + "\n"
                        + "50001-100000：总市值" + value100000 + ",占比：" + value100000.divide(sumValue, 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)).setScale(2)
                        + "% 人数：" + count100000 + ",占比：" + count100000.divide(sumCount, 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)).setScale(2) + "\n"
                        + "100001-150000：总市值" + value150000 + ",占比：" + value150000.divide(sumValue, 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)).setScale(2)
                        + "% 人数：" + count150000 + ",占比：" + count150000.divide(sumCount, 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)).setScale(2) + "\n"
                        + "150001-200000：总市值" + value200000 + ",占比：" + value200000.divide(sumValue, 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)).setScale(2)
                        + "% 人数：" + count200000 + ",占比：" + count200000.divide(sumCount, 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)).setScale(2) + "\n"
                        + "200001-300000：总市值" + value300000 + ",占比：" + value300000.divide(sumValue, 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)).setScale(2)
                        + "% 人数：" + count300000 + ",占比：" + count300000.divide(sumCount, 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)).setScale(2) + "\n"
                        + "300001-500000：总市值" + value500000 + ",占比：" + value500000.divide(sumValue, 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)).setScale(2)
                        + "% 人数：" + count500000 + ",占比：" + count500000.divide(sumCount, 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)).setScale(2) + "\n"
                        + "大于500000：总市值" + more500000 + ",占比：" + more500000.divide(sumValue, 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)).setScale(2)
                        + "% 人数：" + moreCount500000 + ",占比：" + moreCount500000.divide(sumValue, 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)).setScale(2) + "\n";
        account1.forEach(item -> {
            qywxService.sendWeChatMessage(content, item);
        });


    }

    public void sendMsg4() throws Exception {

        DateTime yesterday = DateUtil.yesterday();
        DateTime startTime = DateUtil.beginOfDay(yesterday);
        DateTime endTime = DateUtil.endOfDay(yesterday);
        Integer sumEcologyUserCount = userEcologyHatchRecordsDao.getSumEcologyUserCount();
        Integer sumEcologyUserCountByDate = userEcologyHatchRecordsDao.getSumEcologyUserCountByDate(startTime, endTime);
        List<Map<String, String>> sumCollectionEcologyCount = userEcologyHatchRecordsDao.getSumCollectionEcologyCount();
        StringBuffer content = new StringBuffer();
        Integer sumCount = 0;
        content.append(DateUtil.yesterday().toString("yyyy年MM月dd日") + "生态孵化：\n");
        content.append("总生态孵化参与人数：" + sumEcologyUserCount + "\n");
        content.append("昨日生态孵化参与人数：" + sumEcologyUserCountByDate + "\n");
        for (Map<String, String> stringIntegerMap : sumCollectionEcologyCount) {
            content.append(stringIntegerMap.get("name") + "熔炼人数:").append(MapUtil.getStr(stringIntegerMap, "count") + "\n");
            content.append(stringIntegerMap.get("name") + "熔炼数量:").append(MapUtil.getStr(stringIntegerMap, "usecount") + "\n");
            sumCount += MapUtil.getInt(stringIntegerMap, "usecount");
        }
        content.append("生态孵化藏品总数量：" + sumCount);
        account.forEach(item -> {
            qywxService.sendWeChatMessage(content.toString(), item);
        });
    }

    public void sendMsg2() throws Exception {

        DateTime yesterday = DateUtil.yesterday();
        DateTime yesterdayStartTime = DateUtil.beginOfDay(yesterday);
        DateTime yesterdayEndTime = DateUtil.endOfDay(yesterday);
        String payAmount = payOrderDao.getPayAmount(yesterdayStartTime, yesterdayEndTime, PayTypeEnum.PAY);
        String recAmount = payOrderDao.getPayAmount(yesterdayStartTime, yesterdayEndTime, PayTypeEnum.RECHARGE);
        String withAmount = sandTransferRecordDao.getSumAmount(yesterdayStartTime, yesterdayEndTime);
        String daoAmount = daoTransferDao.getSumSuccessAmount(yesterdayStartTime, yesterdayEndTime);
        int addCzCount = userCollectionDao.getNewAddCount(yesterdayStartTime, yesterdayEndTime, DaoLevelTypeEnum.CITY_LORD.getCode());
        int addJmCount = userCollectionDao.getNewAddCount(yesterdayStartTime, yesterdayEndTime, DaoLevelTypeEnum.RESIDENT.getCode());
        int pay1000Count = payOrderDao.payUserCount(yesterdayStartTime, yesterdayEndTime);

        String content = DateUtil.yesterday().toString("yyyy年MM月dd日") + "收支统计：\n" +
                "充值总金额：" + recAmount + "元\n" +
                "银行卡支付：" + payAmount + "元\n" +
                "用户提现总金额：" + withAmount + "元\n" +
                "企业提现总金额：" + daoAmount + "元\n" +
                "新增居民人数：" + addJmCount + "人\n" +
                "新增城主人数：" + addCzCount + "人\n" +
                "注册消费满1000人数:" + pay1000Count + "人";
        account.forEach(item -> {
            qywxService.sendWeChatMessage(content, item);
        });
    }

    @Scheduled(cron = "0 0 10 1 1/1 ? ")
    public void sendMsg3() throws Exception {
        Long increment = redisTemplate.opsForValue().increment(oneTimeKey);
        redisTemplate.expire(oneTimeKey, 1, TimeUnit.MINUTES);
        if (increment > 1) {
            return;
        }
        DateTime dateTime = DateUtil.lastMonth();
        // 获取上个月的第一天日期
        DateTime startTime = DateUtil.beginOfMonth(dateTime);
        // 获取上个月的最后一天日期
        DateTime endTime = DateUtil.endOfMonth(dateTime);
        // 获取总手续费(包含市值账号)(品牌孵化)
        BigDecimal brandIncubationIncludesMarketCapitalization = secondOrderDao.getMonthlyStatistics(null, 1, startTime, endTime).multiply(BigDecimal.valueOf(0.93)).setScale(2, BigDecimal.ROUND_HALF_UP);
        // 获取总手续费(不包含市值账号)(品牌孵化)
        BigDecimal brandIncubationDoesNotIncludeMarketCapitalization = secondOrderDao.getMonthlyStatistics(1, 1, startTime, endTime).multiply(BigDecimal.valueOf(0.93)).setScale(2, BigDecimal.ROUND_HALF_UP);
        // 获取总手续费(包含市值账号)(自由市场)
        BigDecimal freeMarketsIncludeMarketCapitalization = secondOrderDao.getMonthlyStatistics(null, 2, startTime, endTime).multiply(BigDecimal.valueOf(0.93)).setScale(2, BigDecimal.ROUND_HALF_UP);
        //  获取总手续费(不包含市值账号)(自由市场)
        BigDecimal theFreeMarketDoesNotContainTwoLevels = secondOrderDao.getMonthlyStatistics(1, 2, startTime, endTime).multiply(BigDecimal.valueOf(0.93)).setScale(2, BigDecimal.ROUND_HALF_UP);

        String content = StrUtil.format("{}品牌孵化以及自由市场统计数据: " + "\n" +
                        "品牌孵化总手续费(包含市值账号):{}元,\n" +
                        "品牌孵化仅用户购买手续费(不包含市值账号):{}元,\n" +
                        "品牌孵化仅用户购买手续费平台收益(不包含市值账号):{}元,\n" +
                        "自由市场总手续费(包含市值账号):{}元,\n" +
                        "自由市场仅用户购买手续费(不包含市值账号):{}元,\n" +
                        "自由市场仅用户购买手续费平台收益(不包含市值账号):{}元",
                DateUtil.lastMonth().toString("yyyy年MM月"),
                brandIncubationIncludesMarketCapitalization,
                brandIncubationDoesNotIncludeMarketCapitalization,
                brandIncubationDoesNotIncludeMarketCapitalization.multiply(Convert.toBigDecimal(0.45)),
                freeMarketsIncludeMarketCapitalization,
                theFreeMarketDoesNotContainTwoLevels,
                theFreeMarketDoesNotContainTwoLevels.multiply(Convert.toBigDecimal(0.45)));
        account.forEach(item -> {
            qywxService.sendWeChatMessage(content, item);
        });
    }

//    /**
//     * 每周一 上午9点半 给智沛推送生态收益数据
//     * @throws Exception
//     */
//    @Scheduled(cron = "0 30 8 * * 1 ")
//    public void sendEcologyIncomeData() throws Exception {
//        Long increment = redisTemplate.opsForValue().increment(oneTimeKey);
//        redisTemplate.expire(oneTimeKey,1, TimeUnit.MINUTES);
//        if(increment>1){
//            return;
//        }
//        BigDecimal lastWeekSumIncome = userEcologyHatchIncomeRecordDao.getLastWeekSumIncome();
//        // 获取平台收益
//        List<EcologicalBenefitDTO> capturePlatformRevenueList = userEcologyHatchIncomeRecordDao.capturePlatformRevenue();
//        // 获取dao收益
//        List<EcologicalBenefitDTO> captureDaoRevenueList = userEcologyHatchIncomeRecordDao.captureDaoRevenue();
//        adminAccount.forEach(item->{
//            StringBuffer qyWxMessage = new StringBuffer();
//            qyWxMessage.append(StrUtil.format("{}发放总燃料:{}",DateUtil.format(DateTime.now(),"yyyy年MM月dd日"),lastWeekSumIncome.stripTrailingZeros().toPlainString()));
//            StringBuffer capturePlatformRevenueMessage = new StringBuffer();
//            capturePlatformRevenueMessage.append(StrUtil.format("{}收益明细(平台):",DateUtil.format(DateTime.now(),"yyyy年MM月dd日"))+"\n");
//            for (int i = 0; i < capturePlatformRevenueList.size(); i++) {
//                EcologicalBenefitDTO ecologicalBenefitDTO = capturePlatformRevenueList.get(i);
//                if (i == 0){
//                    qyWxMessage.append(StrUtil.format(" 激励池:{},(平台)节省燃料:{}",ecologicalBenefitDTO.getBonusPoolAmount().setScale(2,BigDecimal.ROUND_DOWN).toPlainString(),ecologicalBenefitDTO.getAmountSaved().setScale(2,BigDecimal.ROUND_DOWN).toPlainString()));
//                }
//                capturePlatformRevenueMessage.append(ecologicalBenefitDTO.getIncomeName() + ":" + ecologicalBenefitDTO.getIncomeAmount().setScale(2,BigDecimal.ROUND_DOWN).toPlainString() + "\n");
//            }
//            qywxService.sendWeChatMessage(qyWxMessage.toString(),item);
//            qywxService.sendWeChatMessage(capturePlatformRevenueMessage.toString(),item);
//
//            StringBuffer captureDaoRevenueMessage = new StringBuffer();
//            captureDaoRevenueMessage.append(StrUtil.format("{}收益明细(DAO):",DateUtil.format(DateTime.now(),"yyyy年MM月dd日"))+"\n");
//            for (int i = 0; i < captureDaoRevenueList.size(); i++) {
//                EcologicalBenefitDTO ecologicalBenefitDTO = captureDaoRevenueList.get(i);
//                captureDaoRevenueMessage.append(ecologicalBenefitDTO.getIncomeName() + ":" + ecologicalBenefitDTO.getIncomeAmount().setScale(2,BigDecimal.ROUND_DOWN).toPlainString() + "\n");
//                captureDaoRevenueMessage.append("激励池 :" + ecologicalBenefitDTO.getBonusPoolAmount().setScale(2,BigDecimal.ROUND_DOWN).toPlainString() + "\n");
//
//            }
//            qywxService.sendWeChatMessage(captureDaoRevenueMessage.toString(),item);
//        });
//    }
}
